package com.earogya.springsecurity.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.earogya.springsecurity.security.AddUsersToUserGroupsInterface;
import com.earogya.springsecurity.security.CreateUsersInterface;

/**
 * 
 * Controller to manage Admin functions
 * 
 * @author Ureka
 *
 */
@Controller
public class AdminController extends BaseController {
	@Autowired
	private CreateUsersInterface createUsersDao;

	@Autowired
	private AddUsersToUserGroupsInterface addUsersToUserGroupsDao;

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/createUsers.do", method = RequestMethod.GET)
	public void showCreateUsersPage() {
	}

	/**
	 * Manage create users
	 * 
	 * @param username
	 * @param name
	 * @param password
	 * @param email
	 * @param department
	 * @return redirect page
	 */
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/createUsers.do", method = RequestMethod.POST)
	public String submitCreatePage(@RequestParam("username") String username,
			@RequestParam("name") String name,
			@RequestParam("password") String password,
			@RequestParam("email") String email,
			@RequestParam("department") String department) {

		try {
			createUsersDao.createUser(username, name, password, email,
					department);
			return "redirect:/admin/add_users_to_user_groups.do?message=User Added Successfully";
		} catch (DuplicateKeyException e) {

			return "redirect:/admin/createUsers.do?message=Username already exists";
		}
	}

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/add_users_to_user_groups.do", method = RequestMethod.GET)
	public void showAddUsersToUserGroupsPage() {
	}

	
	/**
	 * 
	 * Manage add users to user groups
	 * 
	 * @param username
	 * @param userGroup
	 * @return
	 */
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value = "/admin/add_users_to_user_groups.do", method = RequestMethod.POST)
	public String submitAddUsersToUserGroupsPage(
			@RequestParam("username") String username,
			@RequestParam("userGroup") int userGroup) {

		Boolean success = addUsersToUserGroupsDao.addUsersToUserGroups(
				username, userGroup);
		if (success == true) {

			return "redirect:/admin/add_users_to_user_groups.do?message=User Added to User Class";
		} else {
			return "redirect:/admin/add_users_to_user_groups.do?message=User Does not Exist";
		}

	}

}
